package com.lk.register.controller;

import cn.hutool.core.collection.CollUtil;
import com.lk.entity.Service;
import com.lk.dto.ResponseResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 这里暂时不考虑 集群注册中心
 *
 * @author kun.li
 */
@RestController
@RequestMapping("/register")
public class RegisterController {
    private final Map<String, Set<Service>> serviceMap = new ConcurrentHashMap<>();

    /**
     * 服务注册
     *
     * @param service 服务实例
     * @return
     */
    @PostMapping
    public ResponseResult<Void> registerService(@RequestBody Service service) {
        // 同一个服务名称 多个客户端
        Set<Service> serviceSet = serviceMap.get(service.getServiceName());

        if (CollUtil.isNotEmpty(serviceSet)) {
            serviceSet.add(service);
        } else {
            serviceSet = new HashSet<>();
            serviceSet.add(service);
        }
        serviceMap.put(service.getServiceName(), serviceSet);
        return ResponseResult.ok();
    }

    @GetMapping
    public ResponseResult getServiceAll() {
        return ResponseResult.ok(serviceMap);

    }

    /**
     * 根据服务名称获取对应的服务实例
     *
     * @param serviceName 服务名称
     * @return 多个服务实例
     */
    @GetMapping("/{serviceName}")
    public ResponseResult<Set<Service>> getService(@PathVariable String serviceName) {
        Set<Service> service = serviceMap.get(serviceName);
        if (CollUtil.isNotEmpty(serviceMap)) {
            return ResponseResult.ok(service);
        }
        return ResponseResult.ok("该服务没有进行注册", null);

    }

    @GetMapping("removeService")
    public ResponseResult<Void> removeService(String serviceName) {
        Set<Service> services = serviceMap.get(serviceName);
        Iterator<Service> iterator = services.iterator();
        while (iterator.hasNext()) {
            Service next = iterator.next();
            if (next.getServiceName().equals(serviceName)) {
                services.remove(next);
                break;
            }
        }
        return ResponseResult.ok();
    }

}
